package com.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yinxing
 * @date 2022-08-30
 * 队列配置文件代码
 */
@Configuration
public class ShopQueueConfig {

    @Value("${shop.exchange}")
    private String exchange;

    @Value("${shop.queue}")
    private String queue;

    @Value("${shop.routing-key}")
    private String routing_key;

    @Value("${shop.dead-exchange}")
    private String dead_exchange;

    @Value("${shop.dead-queue}")
    private String dead_queue;

    @Value("${shop.dead-routing-key}")
    private String dead_routing_key;

    /**
     * 普通交换机
     * @return
     */
    @Bean("normal_exchange")
    public DirectExchange exchange(){
        return new DirectExchange(exchange);
    }

    /**
     * 死信交换机
     * @return
     */
    @Bean("dead_exchange")
    public DirectExchange dead_exchange(){
        return new DirectExchange(dead_exchange);
    }

    /**
     * 普通队列
     * @return
     */
    @Bean("normal_queue")
    public Queue queue(){
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange",dead_exchange);
        args.put("x-dead-letter-routing-key",dead_routing_key);
        args.put("x-message-ttl",10000);
        return QueueBuilder.durable(queue).withArguments(args).build();
    }

    /**
     * 死信队列
     * @return
     */
    @Bean("dead_queue")
    public Queue dead_Queue(){
        return QueueBuilder.durable(dead_queue).build();
    }

    /**
     * 绑定普通queue与exchange
     * @param queue
     * @param exchange
     * @return
     */
    @Bean
    public Binding queueBinDingExchange(
            @Qualifier("normal_queue") Queue queue,
            @Qualifier("normal_exchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(routing_key);
    }

    /**
     * 绑定死信queue与exchange
     * @param queue
     * @param exchange
     * @return
     */
    @Bean
    public Binding deadQueueBinDingExchange(
            @Qualifier("dead_queue") Queue queue,
            @Qualifier("dead_exchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(dead_routing_key);
    }



}
